import hashlib
import logging

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.utils import timezone
import re
from django.db.models import Q

logger = logging.getLogger(__name__)
UserModel = get_user_model()


class CustomBackend(ModelBackend):
    """
    Django原生认证方式
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        msg = '%s 正在使用本地登录...' % username
        logger.info(msg)
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel.objects.get(Q(email=username)|Q(mobile=username))
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
        else:
            check_password = user.check_password(password)
            if not check_password:
                check_password = user.check_password(hashlib.md5(password.encode(encoding='UTF-8')).hexdigest())
            if check_password and self.user_can_authenticate(user):
                user.last_login = timezone.now()
                user.save()
                return user

# class CustomBackend(ModelBackend):
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         # 1.　todo 不管是用户或者邮箱或者手机号码，第一件事获取对象
#         try:
#             # todo 先通过正则，判断出手机号码/邮箱
#             if re.match(r'^1[\d]{10}$', username):
#                 user = UserModel.objects.get(mobile=username)
#             elif re.match('^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$', username):
#                 user = UserModel.objects.get(email=username)

#         except UserModel.DoesNotExist:
#             user = None

#             # todo 拿到user之后进行校验
#         if user is not None and user.check_password(password):
#             return user
